<template>
  <a-card class="tree-container">
    <a-row style="display: flex">
      <a-input v-model:value.trim="keywords" style="width: 200px" placeholder="请输入物料名称" />
      <a-button type="primary" @click="onsubmit">新建</a-button>
      <a-modal v-model:open="open" :title="formState.categoryId ? '修改' : '添加'" @ok="handleOk">
        <template #footer>
          <a-button key="back" @click="handleCancel">取消</a-button>
          <a-button key="submit" type="primary" :loading="loading" @click="handleOk">确认</a-button>
        </template>
        <a-form
          :model="formState"
          name="basic"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 16 }"
          autocomplete="off"
          @finish="onFinish"
          @finishFailed="onFinishFailed"
        >
          <a-form-item label="分类名称" name="categoryName" :rules="[{ required: true, message: '请输入分类名称' }]">
            <a-input v-model:value="formState.categoryName" placeholder="请输入1分类名称" />
          </a-form-item>
        </a-form>
        <!-- --------------- -->
      </a-modal>
    </a-row>
    <a-row class="sort-flag-row" v-if="props.showMenu"> </a-row>
    <a-tree
      v-if="!_.isEmpty(departmentTreeData)"
      v-model:selectedKeys="selectedKeys"
      v-model:checkedKeys="checkedKeys"
      class="tree"
      :treeData="departmentTreeData"
      :fieldNames="{ title: 'categoryName', key: 'categoryId', value: 'categoryId' }"
      style="width: 100%; overflow-x: auto"
      :style="[!height ? '' : { height: `${height}px`, overflowY: 'auto' }]"
      :showLine="!props.checkable"
      :checkable="props.checkable"
      :checkStrictly="props.checkStrictly"
      :selectable="!props.checkable"
      :defaultExpandAll="true"
      @select="treeSelectChange"
    >
      <template #title="item">
        <a-popover placement="right" v-if="props.showMenu">
          <template #content>
            <div style="display: flex; flex-direction: column">
              <a-button type="text" @click="deleteDepartment(item.categoryId)" v-privilege="'system:department:delete'">删除</a-button>
              <a-button type="text" @click="updateDepartment(item)" v-privilege="'system:department:update'">修改</a-button>
            </div>
          </template>
          {{ item.categoryName }}
          <!--显示排序字段-->
          <template v-if="showSortFlag">
            <span class="sort-span">({{ item.sort }})</span>
          </template>
        </a-popover>
        <div v-else>{{ item.categoryName }}</div>
      </template>
    </a-tree>
    <div class="no-data" v-else>暂无结果</div>
    <!-- 添加编辑部门弹窗 -->
    <!-- <DepartmentFormModal ref="departmentFormModal" @refresh="refresh" /> -->
  </a-card>
</template>
<script setup>
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { onUnmounted, ref, watch, reactive } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import _ from 'lodash';
  import { createVNode, onMounted } from 'vue';
  // import DepartmentFormModal from '../department-form-modal/index.vue';
  // import { departmentApi } from '/@/api/system/department-api';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import departmentEmitter from '../../department-mitt';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { projectMaterialApi } from '/@/api/business/project-material/project-material-api';
  import { categoryApi } from '/@/api/business/category/category-api';
  const emit = defineEmits(['reloadList']);
  const formState = reactive({
    categoryId: undefined,
    categoryName: '',
    categoryType: 2,
    disabledFlag: false,
  });
  const DEPARTMENT_PARENT_ID = 0;
  const loading = ref(false);
  const open = ref(false);

  const onsubmit = () => {
    open.value = true;
  };

  // 用于绑定输入框的值，即新的分类名称
  const categoryName = ref('');

  // 点击确认添加
  const handleOk = async () => {
    loading.value = true;
    console.log(formState)
    try {
      if (formState.categoryId) {
        await categoryApi.updateCategory(formState);
      } else {
        await categoryApi.addCategory(formState);
      }
      queryDepartmentTree();
      emit('reloadList', formState.parentId);
    } catch (error) {
      smartSentry.captureError(error);
    } finally {
      SmartLoading.hide();
    }
    // 去除新分类名称的前后空格，并检查是否为空
    const trimmedName = categoryName.value.trim();
    if (trimmedName !== '') {
      // 将新的分类名称添加到数组中
      categories.value.push(trimmedName);
      // 清空输入框
      categoryName.value = '';
    }
    setTimeout(() => {
      loading.value = false;
      open.value = false;
    }, 2000);
  };
 
  // 编辑
  function updateDepartment(e) {
   formState.categoryName = e.categoryName;
   formState.categoryId = e.categoryId
    open.value = true;
  }
  const handleCancel = () => {
    const formRef = categoryApi.updateCategory()
    formRef.value = formState.categoryName
    console.log(formRef)
    open.value = false;
    queryDepartmentTree();
  };

  // 删除
  function deleteDepartment(categoryId) {
    Modal.confirm({
      title: '提醒',
      icon: createVNode(ExclamationCircleOutlined),
      content: '确定要删除该分类吗?',
      okText: '删除',
      okType: 'danger',
      async onOk() {
        deleteCategory(categoryId);
      },
      cancelText: '取消',
      onCancel() {},
    });
    async function deleteCategory(categoryId) {
      try {
        SmartLoading.show();
        await categoryApi.deleteCategoryById(categoryId);
        message.success('删除成功');
        // 树状图刷新
        queryDepartmentTree();
      } catch (e) {
        smartSentry.captureError(e);
      } finally {
        SmartLoading.hide();
      }
    }
  }
  // ------------------新建-----------------------------
  const onFinish = (values) => {
    console.log('Success:', values);
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  // ----------------------- 组件参数 ---------------------

  const props = defineProps({
    // 是否可以选中
    checkable: {
      type: Boolean,
      default: false,
    },
    // 父子节点选中状态不再关联
    checkStrictly: {
      type: Boolean,
      default: false,
    },
    // 树高度 超出出滚动条
    height: Number,
    // 显示菜单
    showMenu: {
      type: Boolean,
      default: true,
    },
  });

  // ----------------------- 部门树的展示 ---------------------
  const topDepartmentId = ref();
  // 所有部门列表
  const departmentList = ref([]);
  // 部门树形数据
  const departmentTreeData = ref([]);
  // 存放部门id和部门，用于查找
  const idInfoMap = ref(new Map());
  // 是否显示排序字段
  const showSortFlag = ref(false);

  onMounted(() => {
    queryDepartmentTree();
  });

  // 刷新
  async function refresh() {
    await queryDepartmentTree();
    if (currentSelectedDpartmentId.value) {
      selectTree(currentSelectedDpartmentId.value);
    }
  }

  // 查询部门列表并构建 部门树
  async function queryDepartmentTree() {
    var obj = {
      categoryType: 2,
    };
    loading.value = false;
    open.value = false;
    let res = await projectMaterialApi.ClassificationData(obj);
    let data = res.data;
    departmentTreeData.value = data;
  }

  // 构建部门树
  function buildDepartmentTree(data, parentId) {
    let children = data.filter((e) => e.parentId === parentId) || [];
    children.forEach((e) => {
      e.children = buildDepartmentTree(data, e.departmentId);
    });
    updateDepartmentPreIdAndNextId(children);
    return children;
  }

  // 更新树的前置id和后置id
  function updateDepartmentPreIdAndNextId(data) {
    for (let index = 0; index < data.length; index++) {
      if (index === 0) {
        data[index].nextId = data.length > 1 ? data[1].departmentId : undefined;
        continue;
      }

      if (index === data.length - 1) {
        data[index].preId = data[index - 1].departmentId;
        data[index].nextId = undefined;
        continue;
      }

      data[index].preId = data[index - 1].departmentId;
      data[index].nextId = data[index + 1].departmentId;
    }
  }

  // ----------------------- 树的选中 ---------------------
  const selectedKeys = ref([]);
  const checkedKeys = ref([]);
  const breadcrumb = ref([]);
  const currentSelectedDpartmentId = ref();
  const selectedDepartmentChildren = ref([]);

  departmentEmitter.on('selectTree', selectTree);

  function selectTree(id) {
    selectedKeys.value = [id];
    treeSelectChange(selectedKeys.value);
  }

function treeSelectChange(idList) {
    console.log(idList)
    if (_.isEmpty(idList)) {
      breadcrumb.value = [];
      selectedDepartmentChildren.value = [];
      return;
    }
    let id = idList[0];
    selectedDepartmentChildren.value = departmentList.value.filter((e) => e.parentId == id);
    let filterDepartmentList = [];
    recursionFilterDepartment(filterDepartmentList, id, true);
    breadcrumb.value = filterDepartmentList.map((e) => e.name);
  }

  // -----------------------  筛选 ---------------------
  const keywords = ref('');
  watch(
    () => keywords.value,
    () => {
      onSearch();
    }
  );

  // 筛选
  function onSearch() {
    if (!keywords.value) {
      departmentTreeData.value = buildDepartmentTree(departmentList.value, DEPARTMENT_PARENT_ID);
      return;
    }
    let originData = departmentList.value.concat();
    if (!originData) {
      return;
    }
    // 筛选出名称符合的部门
    let filterDepartmenet = originData.filter((e) => e.name.indexOf(keywords.value) > -1);
    let filterDepartmentList = [];
    // 循环筛选出的部门 构建部门树
    filterDepartmenet.forEach((e) => {
      recursionFilterDepartment(filterDepartmentList, e.departmentId, false);
    });

    departmentTreeData.value = buildDepartmentTree(filterDepartmentList, DEPARTMENT_PARENT_ID);
  }

  // 根据ID递归筛选部门
  function recursionFilterDepartment(resList, id, unshift) {
    let info = idInfoMap.value.get(id);
    if (!info || resList.some((e) => e.departmentId == id)) {
      return;
    }
    if (unshift) {
      resList.unshift(info);
    } else {
      resList.push(info);
    }
    if (info.parentId && info.parentId != 0) {
      recursionFilterDepartment(resList, info.parentId, unshift);
    }
  }

  // ----------------------- 表单操作：添加部门/修改部门/删除部门/上下移动 ---------------------
  const departmentFormModal = ref();

  onUnmounted(() => {
    departmentEmitter.all.clear();
  });

  // ----------------------- 以下是暴露的方法内容 ----------------------------
  defineExpose({
    queryDepartmentTree,
    selectedDepartmentChildren,
    breadcrumb,
    selectedKeys,
    checkedKeys,
    keywords,
  });
</script>
<style scoped lang="less">
  .tree-container {
    height: 100%;
    .tree {
      height: 618px;
      margin-top: 10px;
      overflow-x: hidden;
    }

    .sort-flag-row {
      margin-top: 10px;
      margin-bottom: 10px;
    }

    .sort-span {
      margin-left: 5px;
    }
    .no-data {
      margin: 10px;
    }
  }
</style>
